package com.ooono.factorytest.items;

import android.content.Intent;
import android.nfc.NfcAdapter;
import android.nfc.Tag;
import android.os.Bundle;
import android.provider.Settings;
import android.util.Log;
import android.widget.TextView;

import androidx.annotation.Nullable;

import com.ooono.factorytest.R;
import com.ooono.factorytest.base.BaseActivity;

public class NfcTestActivity extends BaseActivity {

    private static final String TAG = "NfcTestActivity";

    public static final String KEY = "nfc";

    NfcAdapter mNfcAdapter;

    private TextView mCardInfo;


    @Override
    public int getTestTitle() {
        return R.string.test_item_nfc;
    }

    @Override
    public String getTestKey() {
        return KEY;
    }

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

    }

    @Override
    public int getContentLayout() {
        return R.layout.content_nfc_test;
    }

    @Override
    public void initViews() {

    }

    @Override
    protected void onResume() {
        super.onResume();
        Log.d(TAG, ">>>-----onResume---------------");
        mCardInfo = findViewById(R.id.nfc_card_info);

        initData();
    }

    /**
     * 初始化数据
     */
    private void initData() {
        mNfcAdapter = NfcAdapter.getDefaultAdapter(this);
        if (mNfcAdapter == null) {
            mCardInfo.setText("Not support NFC");
            Log.d(TAG, "Not support NFC");
        } else if (!mNfcAdapter.isEnabled()) {
            Log.d(TAG, "Please enable NFC first!");
            mCardInfo.setText("Please enable NFC first!");
            Intent intent = new Intent(Settings.ACTION_NFC_SETTINGS);
            // 根据包名打开对应的设置界面
            startActivity(intent);
        } else {
            mCardInfo.setText("NFC 已经启动... \n 请读卡，听到声音即为正常。");
            Log.d(TAG, "NFC enable!");
        }

        Tag tag = getIntent().getParcelableExtra(NfcAdapter.EXTRA_TAG);
        if (tag != null) {
            String id = bytesToHex(tag.getId());
            mCardInfo.setText("读卡成功\n 卡ID是：" + id);
        }
    }

    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
        initData();
    }

    /**
     * 2转16
     */
    private static String bytesToHex(byte[] src){
        StringBuffer sb = new StringBuffer();
        if (src == null || src.length == 0) {
            return null;
        }
        String sTemp;
        for (int i = 0; i < src.length; i++) {
            sTemp = Integer.toHexString(0xFF & src[i]);
            if (sTemp.length() < 2){
                sb.append(0);
            }
            sb.append(sTemp.toUpperCase());
        }
        return sb.toString();
    }

}
